lambda是一種匿名函式,只會以一行作用,其函式雖然簡單但功能卻十分強大
以下是python & javaScript簡單的幾個範例
#表達式用於創建匿名函數
add = lambda x, y: x + y
print(add(3, 5))
#表達是作為排序的key函數
numbers = [(1, 'one'), (3, 'three'), (2, 'two')]
sorted_numbers = sorted(numbers, key=lambda x: x[0])
print(sorted_numbers)
#output: [(1, 'one'), (2, 'two'), (3, 'three')]
#篩選器
numbers = [10,23,6,2,93]
print(list(filter(lambda x: x>=10, numbers)))
#output:[10, 23, 93]
//Lambda 表達式用於創建匿名函數
const multiply = (x, y) => x * y;
console.log(multiply(4, 6));
// output: 24
//Lambda 表達式作為數組的映射函數
const numbers = [1, 2, 3, 4];
const squared = numbers.map(x => x * x);
console.log(squared);
// output: [1, 4, 9, 16]